package com.leon.common.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * 公共的HIbernate操作类 提供CURD
 * 
 * @author leon
 * 
 */
public class CommonDao extends HibernateDaoSupport {

	public void createObject(Object obj) {
		this.getHibernateTemplate().saveOrUpdate(obj);
	}

	public void updateObject(Object obj) {
		this.getHibernateTemplate().update(obj);
	}
	
	@SuppressWarnings("unchecked")
	public Object getObject(Class cls, String id) {
		Object object = this.getHibernateTemplate().get(cls, id);
		return object;
	}

	public void deleteObject(Object obj) {
		this.getHibernateTemplate().delete(obj);
	}
	
	@SuppressWarnings("unchecked")
	public void deleteObject(Class cls,String id){
		Object object=this.getHibernateTemplate().get(cls, id);
		this.getHibernateTemplate().delete(object);
	}

	@SuppressWarnings("unchecked")
	public void deleteObjects(Set objs) {
		for (Object obj : objs) {
			getHibernateTemplate().delete(obj);
		}
	}

	/**
	 * 根据HQL得到查询list
	 * 
	 * @param hql
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List qryObjectByHql(final String hql,final Map<String, Object> params) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if (params != null) {
					for (String key : params.keySet()) {
						query.setParameter(key, params.get(key));
					}
				}
				return query.list();
			}

		});
	}

	/**
	 * 分页HQL查询
	 * 
	 * @param hql
	 * @param params
	 * @param start
	 * @param limit
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List qryObjectByHql(final String hql,
			final Map<String, Object> params, final int start, final int limit) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				if (params != null) {
					for (String key : params.keySet()) {
						query.setParameter(key, params.get(key));
					}
				}
				if(start>=0 && limit>0){
					query.setFirstResult(start);
					query.setMaxResults(limit);
				}
				return query.list();
			}

		});
	}
}
